package cn.rengy.isql;

import cn.rengy.lang.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import java.util.concurrent.Callable;

@Slf4j
//@DS("config")
public class DbSqlValueService {

    private Dao dao;

    private CacheService cacheService;


    public DbSqlValueService(Dao dao, CacheService cacheService) {
        this.dao = dao;
        this.cacheService = cacheService;
    }
    @Value("${dbType:'mysql'}")
    private String dbType;

    public static void main(String[] args) {
        String s="jdbc:opengauss://192.168.8.129:15432/fhyc";
        System.out.println();
    }

    public SqlEntity getSqlEntityByName(String sqlname){
        try {
            return cacheService.getLocalCache("sqlCache", sqlname, new Callable<SqlEntity>() {
                @Override
                public SqlEntity call() throws Exception {
                    SqlEntity sqlEntity=dao.queryForBean("select * from sys_sql where sql_name=?", SqlEntity.class, sqlname);
                    if(sqlEntity==null) {
                        throw new IllegalArgumentException("sqlname["+sqlname+"]不存在");
                    }
                    String sql_value=sqlEntity.getSql_value().trim();
                    //String databaseType=datasourceUrl.split(":")[1];
                    if("opengauss".equals(dbType)||"gauss".equals(dbType)){
                        String gauss_sql_value=sqlEntity.getSqlGauss();
                        if(gauss_sql_value!=null&& !gauss_sql_value.isEmpty()){
                            sql_value=gauss_sql_value.trim();
                        }
                    }
                    String action_type=sql_value.substring(0, 6).toLowerCase();
                    sqlEntity.setAction_type(action_type);
                    //TODO
                    /*
                     *  未做参数值类型处理,
                     数据库varchar字段当做整形传入时会丢失索引
                     可以在sql保存的时候解析 设置 保存
                     */
                    VariableParsedSql parsedSql= SqlParser.parseSql(sql_value);
                    sqlEntity.setParsedSql(parsedSql);
                    if (parsedSql.getNamedParameterCount()>0 ){
                        sqlEntity.setSql_type(_Constant.SqlType.named.name());

                    }else {
                        sqlEntity.setSql_type(_Constant.SqlType.prepared.name());
                    }

                    return sqlEntity;
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
